﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Wolfy.NetDisk.Core.Model;
using Wolfy.NetDisk.Core.Repository;
using Wolfy.NetDisk.Core.Service;

namespace Wolfy.NetDisk.Service
{
    public class CRUDService<T> : ICRUDService<T> where T : DeleteEntity, new()
    {
        protected IRepository<T> repository;
        public CRUDService(IRepository<T> repository)
        {
            this.repository = repository;
        }


        public virtual int Create(T item)
        {
            var newItem = this.repository.Insert(item);
            this.repository.Save();
            return newItem.Id;
        }

        public void Save()
        {
            this.repository.Save();
        }

        public T Get(int id)
        {
            return this.repository.Get(id);
        }

        public IEnumerable<T> GetAll()
        {
            return this.repository.GetAll();
        }

        public IEnumerable<T> Where(Expression<Func<T, bool>> func, bool showDeled = false)
        {
            return this.repository.Where(func, showDeled);
        }

        public void Restore(int id)
        {
            this.repository.Restory(this.repository.Get(id));
            this.repository.Save();
        }

        public void BatchDeleted(params int[] ids)
        {
            foreach (var id in ids)
            {
                this.repository.Get(id).IsDeleted = true;
            }
            this.repository.Save();
        }

        public void BatchRestore(params int[] ids)
        {
            foreach (var id in ids)
            {
                this.repository.Get(id).IsDeleted = false;
            }
            this.repository.Save();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>

        public int Update(T item)
        {
            var t = this.repository.Update(item);
            this.repository.Save();
            return t.Id;
        }
    }
}
